package ui.magic.magiclibs.container.View;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import java.util.Vector;

import ui.magic.magiclibs.container.Linear.LinearMagicUi;

/**
 * Created by liushiyin on 2017/10/22.
 */

public class UnderBar extends LinearMagicUi implements View.OnTouchListener{

    private Vector<View> underMenu;
    private int bgColor;
    private View lastSelectView=null;
    private int menuSelectColor;

    public UnderBar(Context context) {
        super(context);
        init();
    }

    public UnderBar(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public UnderBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        setHorizontal();
        bgColor=0xFFFF4081;
        menuSelectColor=0xFFFFA940;
        this.setAlign(LinearMagicUi.CENTER);
        underMenu=new Vector<>();
        this.setBackgroundColor(bgColor);
    }

    public void addViewMenu(View menu){
        underMenu.add(menu);
        menu.setOnTouchListener(this);
        adjustMenuSize();
    }

    private void adjustMenuSize(){
        int count=underMenu.size();
        int width=100/count;
        for(int i=0;i<count;++i){
            View v=underMenu.get(i);
            this.removeChild(v);
            v.setBackgroundColor(bgColor);
            this.addChild(v,width,100);
        }
    }

    public void setUnderBgColor(int color){
        this.setBackgroundColor(color);
        bgColor=color;
    }

    public void setMenuSelectColor(int color){
        menuSelectColor=color;
    }

    public View getMenuView(int index){
        if(index>underMenu.size()||index<1){
            return null;
        }else{
            return underMenu.get(index-1);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if(event.getAction()==MotionEvent.ACTION_UP){
            if(lastSelectView!=null){
                lastSelectView.setBackgroundColor(bgColor);
            }
            lastSelectView=v;
            lastSelectView.setBackgroundColor(menuSelectColor);
        }
        return false;
    }
}
